<template>
    <el-main>

      <!-- 按钮 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="客户姓名">
          <el-input v-model="filters.clientName" placeholder="请输入客户姓名" clearable @keyup.enter="onSearch"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="success" @click="onReset">重置</el-button>
          <el-button style="margin-left: 100px;" type="primary" @click="onAdd">入住登记</el-button>
          <el-button type="danger" @click="onDeleteAll">一键删除</el-button>
          <el-button type="warning" @click="confirmExport">导出</el-button>
        </el-form-item>
      </el-form>

      <!-- 类型筛选 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-radio-group v-model="filters.clientType" @change="onSearch">
          <el-radio-button label="自理" />
          <el-radio-button label="护理" />
        </el-radio-group>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData"
                style="width: 100%; margin-top: 25px"
                v-loading="loading"
                @selection-change="handleSelectionChange"

                :row-key="'clientId'"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width = "80"></el-table-column>
        <el-table-column prop="clientName" label="客户姓名"></el-table-column>
        <el-table-column prop="clientGender" label="性别"></el-table-column>
        <el-table-column prop="clientAge" label="年龄" ></el-table-column>
        <el-table-column prop="dateOfBirth" label="出生日期" ></el-table-column>
        <el-table-column prop="clientCardNumber" label="身份证号" width = "200"></el-table-column>
        <el-table-column prop="bloodType" label="血型" ></el-table-column>
        <el-table-column prop="familyMember" label="家属" ></el-table-column>
        <el-table-column prop="clientPhone" label="电话号码" ></el-table-column>
        <el-table-column label="操作" width = "200">
          <template #default="scope">
            <el-button size="default" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[6, 10, 20, 50]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
      </div>

      <!-- 入住登记 -->
      <el-dialog v-model="dialogVisible" title="客户入住登记" width="70%" >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px" v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="8"><el-form-item label="客户姓名" prop="clientName"><el-input v-model="formData.clientName" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="出生日期" prop="dateOfBirth"><el-date-picker v-model="formData.dateOfBirth" type="date" placeholder="选择出生日期" style="width: 100%;" @change="calculateAge" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="年龄"><el-input v-model="formData.clientAge" disabled /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="性别" prop="clientGender"><el-radio-group v-model="formData.clientGender"><el-radio label="男" /><el-radio label="女" /></el-radio-group></el-form-item></el-col>
            <el-col :span="16"><el-form-item label="身份证号" prop="clientCardNumber"><el-input v-model="formData.clientCardNumber" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="血型" prop="bloodType"><el-select v-model="formData.bloodType" placeholder="选择血型" style="width: 100%;"><el-option label="A型" value="A"/><el-option label="B型" value="B"/><el-option label="AB型" value="AB"/><el-option label="O型" value="O"/></el-select></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="家属" prop="familyMember"><el-input v-model="formData.familyMember" /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="联系电话" prop="clientPhone"><el-input v-model="formData.clientPhone" /></el-form-item></el-col>

            <el-divider />

            <el-col :span="8"><el-form-item label="楼栋"><el-input value="606" disabled /></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="选择楼层"><el-select v-model="selectedFloor" placeholder="请选择楼层" @change="handleFloorChange" style="width: 100%;"><el-option v-for="floor in availableData.floors" :key="floor" :label="`${floor}层`" :value="floor" /></el-select></el-form-item></el-col>
            <el-col :span="8"><el-form-item label="选择房间">
              <el-select v-model="selectedRoom" placeholder="请先选楼层" @change="handleRoomChange" style="width: 100%;" :disabled="!selectedFloor">
                <el-option v-for="roomId in Object.keys(availableData.beds)" :key="roomId" :label="`${roomId}室`" :value="roomId" />
              </el-select>
            </el-form-item></el-col>
            <el-col :span="8"><el-form-item label="选择床位" prop="bedId">
              <el-select v-model="formData.bedId" placeholder="请先选房间" style="width: 100%;" :disabled="!selectedRoom">
                <el-option v-for="bed in availableData.bedsInRoom" :key="bed.bedId" :label="bed.bedCode" :value="bed.bedId" />
              </el-select>
            </el-form-item></el-col>
            <el-col :span="8"><el-form-item label="客户类型" prop="clientType"><el-radio-group v-model="formData.clientType"><el-radio label="自理" /><el-radio label="护理" /></el-radio-group></el-form-item></el-col>
            <el-col :span="8"></el-col>

            <el-col :span="12"><el-form-item label="入住时间" prop="checkInTime"><el-date-picker v-model="formData.checkInTime" type="datetime" placeholder="选择入住时间" style="width: 100%;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="合同到期时间" prop="contractEndTime"><el-date-picker v-model="formData.contractEndTime" type="datetime" placeholder="选择合同到期时间" style="width: 100%;" /></el-form-item></el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确认登记</el-button>
        </template>
      </el-dialog>

      <!-- 编辑客户对话框 -->
      <el-dialog v-model="editDialog.visible" title="修改客户信息" width="60%">
        <el-form ref="editFormRef" :model="editForm.data" :rules="formRules" label-width="110px" v-loading="editDialog.loading">
          <el-row :gutter="20">
            <el-col :span="12"><el-form-item label="客户姓名" prop="clientName"><el-input v-model="editForm.data.clientName" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="服务类型" prop="clientType"><el-radio-group v-model="editForm.data.clientType"><el-radio label="自理" /><el-radio label="护理" /></el-radio-group></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="出生日期" prop="dateOfBirth"><el-date-picker v-model="editForm.data.dateOfBirth" type="date" style="width: 100%;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="年龄"><el-input v-model="editForm.data.clientAge" disabled /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="性别" prop="clientGender"><el-radio-group v-model="editForm.data.clientGender"><el-radio label="男" /><el-radio label="女" /></el-radio-group></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="身份证号" prop="clientCardNumber"><el-input v-model="editForm.data.clientCardNumber" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="血型" prop="bloodType"><el-select v-model="editForm.data.bloodType" placeholder="选择血型" style="width: 100%;"><el-option label="A型" value="A"/><el-option label="B型" value="B"/><el-option label="AB型" value="AB"/><el-option label="O型" value="O"/></el-select></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="家属" prop="familyMember"><el-input v-model="editForm.data.familyMember" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="联系电话" prop="clientPhone"><el-input v-model="editForm.data.clientPhone" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="合同到期时间" prop="contractEndTime"><el-date-picker v-model="editForm.data.contractEndTime" type="datetime" style="width: 100%;" /></el-form-item></el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="editDialog.loading">确认修改</el-button>
        </template>
      </el-dialog>


    </el-main>
</template>

<script lang="js" setup>
import { ref, reactive, onMounted, nextTick, h, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

import upload from 'element-plus/es/components/upload/index.mjs';
import { getFloors, getAvailableBedsByFloor } from '@/api/apiList/bed.js';
import {
  clientList,
  deleteClient,
  restoreClient,
  batchDeleteClients,
  submitCheckIn,
  updateClient,
  getClientDetails,
  exportClients
} from '@/api/apiList/client'


const clientId = ref('');
const clientName = ref('');
const clientType = ref('');
const clientGender = ref('');
const clientAge = ref('');
const dateOfBirth = ref('');
const clientCardNumber = ref('');
const bloodType = ref('');
const familyMember = ref('');
const clientPhone = ref('');


const dialogVisible = ref(false);
const editDialogVisible = ref(false);
// const detailDialogVisible = ref(false); // 新增的弹窗可见状态
const formRef = ref(null);

// 表格和加载状态
const tableData = ref([]);
const loading = ref(false);
const selectedClientIds = ref([]); // 用于存储选中的客户ID

// --- 编辑功能所需的状态 ---
const editFormRef = ref(null);
const editDialog = reactive({
  visible: false,
  loading: false,
});
const editForm = reactive({
  data: {},
});
const currentEditingClientId = ref(null);

//新增
const getInitialFormData = () => ({
  clientName: '张珍娜', clientType: '护理', dateOfBirth: null, clientAge: null,
  clientGender: '女', clientCardNumber: '421302200411110022', bloodType: '', familyMember: '张筱雨', clientPhone: '12244445555',
  bedId: null, checkInTime: new Date(), contractEndTime: null, adId: 1, // 假设管理员ID为1
});
const formData = reactive(getInitialFormData());

const selectedFloor = ref(null);
const selectedRoom = ref(null);
const availableData = reactive({ floors: [], beds: {}, bedsInRoom: [] });

const filters = reactive({
  clientName: '',
  clientType: '自理' // 默认值，与后端匹配
});

// 将所有分页数据整合到一个 reactive 对象中
const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 6
});

// --- 校验规则 ---
const validateContractTime = (rule, value, callback) => {
  if (value && formData.checkInTime && new Date(value) <= new Date(formData.checkInTime)) {
    callback(new Error('合同到期时间必须晚于入住时间'));
  } else {
    callback();
  }
};
const formRules = reactive({
  clientName: [{ required: true, message: '请输入客户姓名', trigger: 'change' }],
  clientGender: [{ required: true, message: '请输入客户性别', trigger: 'change' }],
  dateOfBirth: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  bedId: [{ required: true, message: '请选择床位', trigger: 'change' }],
  clientCardNumber: [
    { required: true, message: '请输入身份证号', trigger: 'change' },
    { len: 18, message: '身份证号必须为18位', trigger: 'blur' }
  ],
  bloodType: [{ required: true, message: '请输入客户血型', trigger: 'change' }],
  familyMember: [{ required: true, message: '请输入客户家属', trigger: 'change' }],
  clientPhone: [{ required: true, message: '请输入客户电话', trigger: 'change' }],
  clientType: [{ required: true, message: '请输入客户类型', trigger: 'change' }],
  checkInTime: [{ required: true, message: '请选择入住时间', trigger: 'change' }],
  contractEndTime: [
    { required: true, message: '请选择合同到期时间', trigger: 'change' },
    { validator: validateContractTime, trigger: 'change' }
  ],
});

// --- 方法定义 ---
async function fetchClientList() {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      query: {
        clientName: filters.clientName,
        clientType: filters.clientType
      }
    };
    const pageData = await clientList(params);

    tableData.value = pageData.records;
    pagination.total = pageData.total;

  } catch (error) {
    // 错误提示已经在拦截器中弹出，这里只需在控制台记录以方便调试。
    console.error("在组件层捕获到API调用错误:", error);
  } finally {
    // 无论成功还是失败，最后都结束加载状态
    loading.value = false;
  }
}

function onSearch() {
  pagination.currentPage = 1;
  fetchClientList();
}

function onReset() {
  filters.clientName = '';
  filters.clientType = '自理';
  pagination.currentPage = 1;
  fetchClientList();
}

function handlePageChange(newPage) {
  pagination.currentPage = newPage;
  fetchClientList();
}

function handleSizeChange(newSize) {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchClientList();
}

const handleSelectionChange = (selection) => {
  selectedClientIds.value = selection.map(item => item.clientId);
};

// 单个删除
async function onDelete(row) {
  try {
    await ElMessageBox.confirm(`确认删除客户 "${row.clientName}"？`, '提示', { type: 'warning' });

    await deleteClient(row.clientId);

    // 显示带“撤销”按钮的成功提示
    showUndoMessage(row.clientId, row.clientName);

    // 刷新列表以移除“已删除”项 (如果您的查询排除了 status=0 的话)
    fetchClientList();
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除失败', err);
      // ElMessage错误提示已由拦截器处理
    }
  }
}

// 批量删除
async function onDeleteAll() {
  if (selectedClientIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的客户');
    return;
  }
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedClientIds.value.length} 位客户？ 注意：此操作不可逆！！！`, '提示', { type: 'warning' });

    await batchDeleteClients(selectedClientIds.value);

    ElMessage.success('批量删除成功');

    // 清空选择并刷新列表
    // this.$refs.tableRef.clearSelection(); // 在Options API中
    // 在 setup 中需要获取table的ref实例来调用
    fetchClientList();
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量删除失败', err);
    }
  }
}

// 显示带“撤销”按钮的成功提示
function showUndoMessage(clientId, clientName) {
  // 使用 h 函数创建虚拟DOM
  const messageVNode = h('div', null, [
    h('span', null, `客户 "${clientName}" 删除成功！ `),
    h('a', {
      style: 'color: #409EFF; cursor: pointer; text-decoration: underline;',
      onClick: async () => {
        try {
          await restoreClient(clientId);
          ElMessage.success(`已成功撤销对 "${clientName}" 的删除操作`);
          fetchClientList(); // 撤销后刷新列表
        } catch (err) {
          // ElMessage错误提示已由拦截器处理
        }
      }
    }, '点此撤销')
  ]);

  ElMessage({
    message: messageVNode,
    type: 'success',
    duration: 3000 // 持续3秒，给用户足够时间点击
  });
}

//新增
const onAdd = () => {
  Object.assign(formData, getInitialFormData());
  selectedFloor.value = null;
  selectedRoom.value = null;
  availableData.beds = {};
  availableData.bedsInRoom = [];
  if (formRef.value) formRef.value.clearValidate();
  dialogVisible.value = true;
};

const calculateAge = (dob) => {
  if (!dob) {
    formData.clientAge = null;
    return;
  }
  const today = new Date();
  const birthDate = new Date(dob);
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  formData.clientAge = age;
};

// 监听出生日期变化，自动计算年龄
watch(() => formData.dateOfBirth, (newDob) => {
  calculateAge(newDob);
});

async function fetchInitialData() {
  loading.value = true;
  try {
    const res = await getFloors();
    availableData.floors = res; // 假设拦截器已处理
  } catch (e) { console.error(e) }
  finally { loading.value = false; }
}

async function handleFloorChange(floorId) {
  selectedRoom.value = null;
  formData.bedId = null;
  availableData.beds = {};
  availableData.bedsInRoom = [];
  if (!floorId) return;

  try {
    const bedsMap = await getAvailableBedsByFloor(floorId);
    // FIX: 检查返回的房间列表是否为空，并给出提示
    if (Object.keys(bedsMap).length === 0) {
      ElMessage.warning('该楼层当前没有空闲房间');
    } else {
      availableData.beds = bedsMap;
    }
  } catch (e) {
    console.error('获取可用床位失败:', e);
  }
}

function handleRoomChange(roomId) {
  formData.bedId = null;
  availableData.bedsInRoom = availableData.beds[roomId] || [];
}

async function submitForm() {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await submitCheckIn(formData);
        ElMessage.success('客户入住登记成功！');
        dialogVisible.value = false;
        fetchClientList();
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false;
      }
    }
  });
}

// 打开编辑对话框并加载数据
async function openEditDialog(row) {
  editDialog.loading = true;
  editDialog.visible = true;
  try {
    // API返回的就是一个可以直接用于表单的DTO对象
    const dto = await getClientDetails(row.clientId);
    // console.log(dto);
    editForm.data = dto;
  } catch (error) {
    console.error("获取客户详情失败:", error);
  } finally {
    editDialog.loading = false;
  }
}

// 提交编辑表单
async function submitEditForm() {
  if (!editFormRef.value) return;
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editDialog.loading = true;
      try {
        // 直接将包含clientId的整个表单数据对象传递给API
        await updateClient(editForm.data);
        ElMessage.success('客户信息更新成功！');
        editDialog.visible = false;
        fetchClientList(); // 刷新主列表数据
      } catch (error) {
        console.error("更新失败:", error);
      } finally {
        editDialog.loading = false;
      }
    }
  });
}

// 监听出生日期变化，自动计算年龄
watch(() => editForm.data.dateOfBirth, (newDob) => {
  calculateAge(newDob);
});

// --- 生命周期钩子 ---
onMounted(() => {
  fetchClientList();
  fetchInitialData();
});

//导出
const confirmExport = () => {
    ElMessageBox.confirm('是否确认导出所有客户信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        exportClient();
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消导出',
        });
    });
};
const exportClient = async () => {
  try {
    // 调用API获取文件Blob
    // 注意：拦截器可能会尝试解析Blob为JSON而出错，需要确保拦截器能正确处理
    const blob = await exportClients();
    // 创建一个临时的URL指向该Blob
    const url = window.URL.createObjectURL(new Blob([blob]));
    // 创建一个隐藏的<a>标签来触发下载
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', '客户信息表.xlsx');

    document.body.appendChild(link);
    link.click();

    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出任务已开始');

  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
};

</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.custom-form .el-form-item{
  margin-top: 25px;
  margin-bottom: 30px
}
.el-upload__tip{
  line-height: 1;
  color: red;
}

.dialog-section {
  border-bottom: 1px solid #eaeaea;
  padding: 10px 0;
}
.dialog-header {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
}
.client-name {
  flex: 1;
}
.client-cover {
  flex: 1;
  text-align: center;
}
.cover-frame {
  display: inline-block;
  border: 1px dashed #ccc;
  padding: 5px;
  width: 150px;
  height: 150px;
}
.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}


</style>
